<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            padding: 20px;
            background-color: #f5f5f5;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .admin-title {
            font-size: 24px;
            font-weight: bold;
        }

        .search-area {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .search-box {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 250px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }

        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }

        .btn-secondary {
            background-color: #2196F3;
            color: white;
        }

        .btn-danger {
            background-color: #f44336;
            color: white;
        }

        .status-text {
            margin-left: 10px;
            font-size: 14px;
            color: #666;
        }

        .success-text {
            color: #4CAF50;
        }

        .error-text {
            color: #f44336;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        .editable {
            border: 1px solid #ddd;
            padding: 5px;
            border-radius: 3px;
            min-width: 100px;
        }

        .action-btns {
            display: flex;
            gap: 5px;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="admin-title">用户管理系统</div>
        <div class="admin-label">Admin</div>
    </div>

    <div class="search-area">
        <input type="text" id="email-search" class="search-box" placeholder="根据邮箱搜索用户">
        <button id="search-by-email" class="btn btn-secondary">搜索</button>

        <input type="text" id="id-search" class="search-box" placeholder="根据ID搜索用户">
        <button id="search-by-id" class="btn btn-secondary">搜索</button>

        <button id="show-all" class="btn btn-primary">显示全部用户</button>

        <button id="add-user" class="btn btn-primary">新增用户</button>
        <span id="status-text" class="status-text"></span>
    </div>

    <table id="user-table">
        <thead>
            <tr>
                <th>用户名</th>
                <th>ID</th>
                <th>邮箱</th>
                <th>密码</th>
                <th>角色</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- 用户数据将通过JS动态填充 -->
        </tbody>
    </table>

    <script>
        // 获取DOM元素
        const userTable = document.getElementById('user-table');
        const tbody = userTable.querySelector('tbody');
        const showAllBtn = document.getElementById('show-all');
        const statusText = document.getElementById('status-text');
        const addUserBtn = document.getElementById('add-user');
        const searchByEmailBtn = document.getElementById('search-by-email');
        const searchByIdBtn = document.getElementById('search-by-id');

        // 当前编辑状态
        let isAddingUser = false;
        let editingUserId = null;

        // 加载所有用户
        function loadAllUsers() {
            fetch('/admin/search/all', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({})
            })
            .then(response => response.json())
            .then(data => {
                renderUserTable(data);
                statusText.textContent = "查询到全部用户";
                statusText.className = "status-text success-text";
            })
            .catch(error => {
                statusText.textContent = "加载用户失败";
                statusText.className = "status-text error-text";
                console.error('Error:', error);
            });
        }

        // 渲染用户表格
        function renderUserTable(users) {
            tbody.innerHTML = '';

            users.forEach(user => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td><span class="editable" data-field="user_name">${user.user_name || ''}</span></td>
                    <td>${user.user_id || ''}</td>
                    <td><span class="editable" data-field="user_mail">${user.user_mail || ''}</span></td>
                    <td><span class="editable" data-field="user_password">${user.user_password || ''}</span></td>
                    <td><span class="editable" data-field="user_role">${user.user_role || ''}</span></td>
                    <td class="action-btns">
                        <button class="btn btn-danger delete-btn" data-id="${user.user_id}">删除</button>
                        <button class="btn btn-secondary edit-btn" data-id="${user.user_id}">修改</button>
                        <button class="btn btn-primary save-btn" data-id="${user.user_id}" style="display:none;">提交</button>
                    </td>
                `;
                tbody.appendChild(tr);
            });

            // 添加事件监听
            addEventListeners();
        }

        // 添加事件监听
        function addEventListeners() {
            // 删除按钮
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    deleteUser(userId);
                });
            });

            // 修改按钮
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    startEditing(userId);
                });
            });

            // 提交按钮
            document.querySelectorAll('.save-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    saveUserChanges(userId);
                });
            });
        }

        // 删除用户
        function deleteUser(userId) {
            if (confirm('确定要删除这个用户吗？')) {
                fetch('/admin/delete/by_user_id', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        user_id: userId,
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.state === 'success') {
                        statusText.textContent = "删除成功";
                        statusText.className = "status-text success-text";
                        loadAllUsers();
                    } else {
                        statusText.textContent = "删除失败";
                        statusText.className = "status-text error-text";
                    }
                })
                .catch(error => {
                    statusText.textContent = "删除失败";
                    statusText.className = "status-text error-text";
                    console.error('Error:', error);
                });
            }
        }

        // 开始编辑用户
        function startEditing(userId) {
            editingUserId = userId;
            const row = document.querySelector(`.edit-btn[data-id="${userId}"]`).closest('tr');

            // 显示保存按钮，隐藏修改按钮
            row.querySelector('.edit-btn').style.display = 'none';
            row.querySelector('.save-btn').style.display = 'inline-block';

            // 使所有可编辑字段可编辑
            row.querySelectorAll('.editable').forEach(field => {
                field.contentEditable = true;
                field.style.border = '1px solid #4CAF50';
            });
        }

        // 保存用户修改
        function saveUserChanges(userId) {
            const row = document.querySelector(`.save-btn[data-id="${userId}"]`).closest('tr');
            const updatedData = {
                user_id: userId,
                user_name: row.querySelector('[data-field="user_name"]').textContent,
                user_mail: row.querySelector('[data-field="user_mail"]').textContent,
                user_password: row.querySelector('[data-field="user_password"]').textContent,
                user_role: row.querySelector('[data-field="user_role"]').textContent
            };

            fetch('/admin/update/by_user_id', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(updatedData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.state === 'success') {
                    statusText.textContent = "修改成功";
                    statusText.className = "status-text success-text";

                    // 退出编辑模式
                    row.querySelector('.edit-btn').style.display = 'inline-block';
                    row.querySelector('.save-btn').style.display = 'none';

                    row.querySelectorAll('.editable').forEach(field => {
                        field.contentEditable = false;
                        field.style.border = '1px solid #ddd';
                    });
                } else {
                    statusText.textContent = "修改失败";
                    statusText.className = "status-text error-text";
                }
            })
            .catch(error => {
                statusText.textContent = "修改失败";
                statusText.className = "status-text error-text";
                console.error('Error:', error);
            });
        }

        // 添加新用户
        function addNewUser() {
            if (isAddingUser) return;

            isAddingUser = true;
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><span class="editable" data-field="user_name" contenteditable="true" style="border:1px solid #4CAF50"></span></td>
                <td>新用户</td>
                <td><span class="editable" data-field="user_mail" contenteditable="true" style="border:1px solid #4CAF50"></span></td>
                <td><span class="editable" data-field="user_password" contenteditable="true" style="border:1px solid #4CAF50"></span></td>
                <td><span class="editable" data-field="user_role" contenteditable="true" style="border:1px solid #4CAF50">user</span></td>
                <td class="action-btns">
                    <button class="btn btn-primary save-new-btn">提交</button>
                    <button class="btn btn-danger cancel-btn">取消</button>
                </td>
            `;
            tbody.prepend(tr);

            // 添加事件监听
            tr.querySelector('.save-new-btn').addEventListener('click', saveNewUser);
            tr.querySelector('.cancel-btn').addEventListener('click', cancelAddUser);
        }

        // 保存新用户
        function saveNewUser() {
            const row = this.closest('tr');
            const newUser = {
                user_name: row.querySelector('[data-field="user_name"]').textContent,
                user_mail: row.querySelector('[data-field="user_mail"]').textContent,
                user_password: row.querySelector('[data-field="user_password"]').textContent,
                user_role: row.querySelector('[data-field="user_role"]').textContent || 'user'
            };

            fetch('/admin/add/new_user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(newUser)
            })
            .then(response => response.json())
            .then(data => {
                if (data.state === 'success') {
                    statusText.textContent = "添加用户成功";
                    statusText.className = "status-text success-text";
                    isAddingUser = false;
                    loadAllUsers();
                } else {
                    statusText.textContent = "添加用户失败";
                    statusText.className = "status-text error-text";
                }
            })
            .catch(error => {
                statusText.textContent = "添加用户失败";
                statusText.className = "status-text error-text";
                console.error('Error:', error);
            });
        }

        // 取消添加新用户
        function cancelAddUser() {
            this.closest('tr').remove();
            isAddingUser = false;
        }

        // 按邮箱搜索
        function searchByEmail() {
            const email = document.getElementById('email-search').value.trim();
            if (!email) return;

            fetch('/admin/search/by_mail', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    user_mail: email
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.state === 'success') {
                    renderUserTable([data.data]);
                    statusText.textContent = "查询成功";
                    statusText.className = "status-text success-text";
                } else {
                    statusText.textContent = "未找到该用户";
                    statusText.className = "status-text error-text";
                    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;">未找到匹配的用户</td></tr>';
                }
            })
            .catch(error => {
                statusText.textContent = "查询失败";
                statusText.className = "status-text error-text";
                console.error('Error:', error);
            });
        }

        // 按ID搜索
        function searchById() {
            const id = document.getElementById('id-search').value.trim();
            if (!id) return;

            fetch('/admin/search/by_user_id',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    user_id: id
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.state === 'success') {
                    renderUserTable([data.data]);
                    statusText.textContent = "查询成功";
                    statusText.className = "status-text success-text";
                } else {
                    statusText.textContent = "未找到该用户";
                    statusText.className = "status-text error-text";
                    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;">未找到匹配的用户</td></tr>';
                }
            })
            .catch(error => {
                statusText.textContent = "查询失败";
                statusText.className = "status-text error-text";
                console.error('Error:', error);
            });
        }

        // 事件绑定
        showAllBtn.addEventListener('click', loadAllUsers);
        addUserBtn.addEventListener('click', addNewUser);
        searchByEmailBtn.addEventListener('click', searchByEmail);
        searchByIdBtn.addEventListener('click', searchById);

        // 初始加载
        loadAllUsers();
    </script>
</body>
</html>